'use client';

import { useForm, SubmitHandler } from 'react-hook-form';
import FormInput from "@/components/ui/Forms/FormElements/FormInput";
import FormSelect from "@/components/ui/Forms/FormElements/FormSelect";
import Button from "@/components/ui/Button/Button";
import { TypeVehicle } from "@/shared/types";
import { saveVehicle } from "@/lib/data";
import styles from "./AddVehicleForm.module.css"

type TypeVehicleFormInputs = {
    registration_number: string;
    vehicle_type: string;
};

const vehicleTypeOptions = [
    { value: 'car_3m_3.5w', label: 'Мотоцикл' },
    { value: 'car_6m_3.5w', label: 'Легковая' },
    { value: 'car_6m_6w', label: 'Грузовик' },
    { value: 'car_12m_8w', label: 'Прицеп' },
];

export default function AddVehicleForm() {
    const { register,
        handleSubmit,
        formState: { errors }, setValue,
        reset
    } = useForm<TypeVehicleFormInputs>();

    const onSubmit: SubmitHandler<TypeVehicleFormInputs> = async (data) => {
        try {
            const match = data.vehicle_type.match(/(\d+(?:\.\d+)?)m_(\d+(?:\.\d+)?)w/)!;
            const vehicle: TypeVehicle = {
                registration_number: data.registration_number.toUpperCase(),
                vehicle_type: vehicleTypeOptions.find(option => option.value === data.vehicle_type)?.label || '',
                length: parseFloat(match[1]),
                weight: parseFloat(match[2]),
            };
            await saveVehicle(vehicle);
            reset();

        } catch (error) {
            console.error('Ошибка при сохранении транспортного средства:', error);
        }
    };

    return (
        <form className={styles.addForm_container} onSubmit={handleSubmit(onSubmit)}>
            <FormInput<TypeVehicleFormInputs>
                id="registration_number"
                type="text"
                name="registration_number"
                kind="registration_number"
                label="Введите номер ТС"
                mask="****** 999"
                placeholder="AA000A 72"
                register={register}
                rules={{
                    required: "Номер транспорта обязателен",
                    minLength: {
                        value: 9,
                        message: "Введите все символы номера"
                    }
                }}
                errors={errors}
            />

            <FormSelect<TypeVehicleFormInputs>
                id="vehicle_type"
                name="vehicle_type"
                label="Выберите тип ТС"
                options={vehicleTypeOptions}
                register={register}
                rules={{ required: "Тип транспорта обязателен" }}
                errors={errors}
            />

            <Button type="submit" kind="submit" content="Сохранить транспорт" />
        </form>
    );
}
